package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.ContestAnnouncement;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.service.ContestAnnouncementService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 竞赛公告接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/contest-announcement")
@Slf4j
public class ContestAnnouncementController {

    @Resource
    private ContestAnnouncementService contestAnnouncementService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建竞赛公告
     *
     * @param contestAnnouncement
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addContestAnnouncement(@RequestBody ContestAnnouncement contestAnnouncement, HttpServletRequest request) {
        if (contestAnnouncement == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        contestAnnouncement.setUserId(loginUser.getId());
        
        boolean result = contestAnnouncementService.save(contestAnnouncement);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newContestAnnouncementId = contestAnnouncement.getId();
        return ResultUtils.success(newContestAnnouncementId);
    }

    /**
     * 删除竞赛公告
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteContestAnnouncement(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        ContestAnnouncement oldContestAnnouncement = contestAnnouncementService.getById(id);
        ThrowUtils.throwIf(oldContestAnnouncement == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = contestAnnouncementService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新竞赛公告
     *
     * @param contestAnnouncement
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateContestAnnouncement(@RequestBody ContestAnnouncement contestAnnouncement, HttpServletRequest request) {
        if (contestAnnouncement == null || contestAnnouncement.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断是否存在
        ContestAnnouncement oldContestAnnouncement = contestAnnouncementService.getById(contestAnnouncement.getId());
        ThrowUtils.throwIf(oldContestAnnouncement == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = contestAnnouncementService.updateById(contestAnnouncement);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取竞赛公告
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<ContestAnnouncement> getContestAnnouncementById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ContestAnnouncement contestAnnouncement = contestAnnouncementService.getById(id);
        if (contestAnnouncement == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(contestAnnouncement);
    }

    /**
     * 根据竞赛ID获取公告列表
     *
     * @param contestId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/by-contest")
    public BaseResponse<Page<ContestAnnouncement>> getAnnouncementsByContestId(
            @RequestParam Long contestId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        if (contestId == null || contestId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        Page<ContestAnnouncement> contestAnnouncementPage = contestAnnouncementService.lambdaQuery()
                .eq(ContestAnnouncement::getContestId, contestId)
                .orderByDesc(ContestAnnouncement::getCreateTime)
                .page(new Page<>(current, size));
        return ResultUtils.success(contestAnnouncementPage);
    }

    /**
     * 根据竞赛ID获取置顶公告列表
     *
     * @param contestId
     * @return
     */
    @GetMapping("/list/pinned")
    public BaseResponse<List<ContestAnnouncement>> getPinnedAnnouncementsByContestId(@RequestParam Long contestId) {
        if (contestId == null || contestId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        List<ContestAnnouncement> pinnedAnnouncements = contestAnnouncementService.lambdaQuery()
                .eq(ContestAnnouncement::getContestId, contestId)
//                .eq(ContestAnnouncement::getIs_pinned, true)
                .orderByDesc(ContestAnnouncement::getCreateTime)
                .list();
        return ResultUtils.success(pinnedAnnouncements);
    }

    /**
     * 分页获取竞赛公告列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ContestAnnouncement>> listContestAnnouncementByPage(@RequestParam long current, @RequestParam long size) {
        Page<ContestAnnouncement> contestAnnouncementPage = contestAnnouncementService.page(new Page<>(current, size));
        return ResultUtils.success(contestAnnouncementPage);
    }

    /**
     * 置顶/取消置顶公告
     *
     * @param id
     * @param isPinned
     * @param request
     * @return
     */
    @PostMapping("/pin")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> pinContestAnnouncement(
            @RequestParam Long id,
            @RequestParam Boolean isPinned,
            HttpServletRequest request) {
        if (id == null || id <= 0 || isPinned == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        ContestAnnouncement contestAnnouncement = contestAnnouncementService.getById(id);
        ThrowUtils.throwIf(contestAnnouncement == null, ErrorCode.NOT_FOUND_ERROR);
        
//        contestAnnouncement.setIs_pinned(isPinned);
        boolean result = contestAnnouncementService.updateById(contestAnnouncement);
        return ResultUtils.success(result);
    }

    /**
     * 发布/取消发布公告
     *
     * @param id
     * @param isPublished
     * @param request
     * @return
     */
    @PostMapping("/publish")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> publishContestAnnouncement(
            @RequestParam Long id,
            @RequestParam Boolean isPublished,
            HttpServletRequest request) {
        if (id == null || id <= 0 || isPublished == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        ContestAnnouncement contestAnnouncement = contestAnnouncementService.getById(id);
        ThrowUtils.throwIf(contestAnnouncement == null, ErrorCode.NOT_FOUND_ERROR);
        
//        contestAnnouncement.setIs_published(isPublished);
        boolean result = contestAnnouncementService.updateById(contestAnnouncement);
        return ResultUtils.success(result);
    }

    /**
     * 根据创建者获取公告列表
     *
     * @param createdBy
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/list/by-creator")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ContestAnnouncement>> getAnnouncementsByCreator(
            @RequestParam Long createdBy,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        if (createdBy == null || createdBy <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        Page<ContestAnnouncement> contestAnnouncementPage = contestAnnouncementService.lambdaQuery()
                .eq(ContestAnnouncement::getCreateTime, createdBy)
                .orderByDesc(ContestAnnouncement::getCreateTime)
                .page(new Page<>(current, size));
        return ResultUtils.success(contestAnnouncementPage);
    }

    /**
     * 搜索竞赛公告
     *
     * @param keyword
     * @param contestId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<Page<ContestAnnouncement>> searchContestAnnouncements(
            @RequestParam String keyword,
            @RequestParam(required = false) Long contestId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        if (keyword == null || keyword.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        Page<ContestAnnouncement> contestAnnouncementPage = contestAnnouncementService.lambdaQuery()
                .and(wrapper -> wrapper
                        .like(ContestAnnouncement::getTitle, keyword)
                        .or()
                        .like(ContestAnnouncement::getContent, keyword)
                )
                .eq(contestId != null, ContestAnnouncement::getContestId, contestId)
//                .eq(ContestAnnouncement::get, true)
                .orderByDesc(ContestAnnouncement::getCreateTime)
                .page(new Page<>(current, size));
        return ResultUtils.success(contestAnnouncementPage);
    }

    /**
     * 批量删除竞赛公告
     *
     * @param ids
     * @param request
     * @return
     */
    @PostMapping("/batch/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchDeleteContestAnnouncements(@RequestBody List<Long> ids, HttpServletRequest request) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = contestAnnouncementService.removeByIds(ids);
        return ResultUtils.success(result);
    }

    /**
     * 批量发布竞赛公告
     *
     * @param ids
     * @param request
     * @return
     */
    @PostMapping("/batch/publish")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchPublishContestAnnouncements(@RequestBody List<Long> ids, HttpServletRequest request) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        List<ContestAnnouncement> announcements = contestAnnouncementService.listByIds(ids);
//        announcements.forEach(announcement -> announcement.setIs_published(true));
        
        boolean result = contestAnnouncementService.updateBatchById(announcements);
        return ResultUtils.success(result);
    }

}